#!/bin/bash
usage="
Author  : Hyunmin Kim (hyun.kim@ucdenver.edu)
Tool    : fisher's exact test for contingency tables
Usage   : cat <input> | $0

<input> : four columns of [x, ~x, y, ~y]

[optioNS]
 -h : show help
 -t : show example
"

function test {
    cmd="echo -e \"10\t100\t20\t120\" | $0"
    echo $cmd
    echo "# this should spit out:"
    eval $cmd
}

## get options
while getopts "th" arg; do
    case $arg in
        t) test; exit 0;;
        h) echo "$usage"; exit 0;;
        *) echo "$usage"; exit 0;;
    esac
done
shift $(( OPTIND - 1 ));


## check if stdin is open
if [ -t 0 ]; then
    echo "$usage"
    exit 0
fi

out=$(mktemp)
rfile=$(mktemp)
rcmd='
## test fishers exact test
    tt=read.table("stdin",header=F);
    pval=apply(tt,1,function(x){
        fisher.test(matrix(x,nrow=2,byrow=T),hybrid=T)$p.value;
    });
    tt$pval = pval;
    write.table(tt$pval,file="OUTPUT",sep="\t",col.names=F,row.names=F);
'
rcmd=${rcmd/OUTPUT/$out}
echo "$rcmd" > $rfile
R --vanilla -f $rfile &>2
cat $out
